<template>
  <div class="rescue-record-page">
    <el-card class="main-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Document /></el-icon>
            <span class="header-title">救助记录管理</span>
          </div>
          <el-button type="primary" @click="openDialog()" :icon="Plus">
            新增救助记录
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索编号、动物类型、地点"
          clearable
          style="max-width: 250px;"
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select 
          v-model="filterStatus" 
          placeholder="选择状态" 
          clearable
          style="width: 150px;"
          @change="handleSearch"
        >
          <el-option label="全部" value="" />
          <el-option label="待审核" :value="0" />
          <el-option label="进行中" :value="1" />
          <el-option label="已完成" :value="2" />
          <el-option label="驳回" :value="3" />
        </el-select>
        <el-button type="primary" @click="handleSearch" :icon="Search">查询</el-button>
        <el-button @click="handleReset" :icon="Refresh">重置</el-button>
      </div>

      <!-- 表格 -->
      <el-table 
        :data="tableData" 
        border 
        stripe
        v-loading="loading"
        style="width: 100%; margin-top: 20px;"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: '600' }"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="rescueCode" label="救助编号" width="180" align="center">
          <template #default="{ row }">
            <span class="code-text">{{ row.rescueCode || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="animalType" label="动物类型" width="120" align="center">
          <template #default="{ row }">
            <el-tag type="info" size="small">{{ row.animalType || '-' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span :title="row.description">{{ row.description || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="发现地点" width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="location-cell">
              <el-icon><Location /></el-icon>
              <span>{{ row.location || '-' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="photo" label="现场照片" width="150" align="center">
          <template #default="{ row }">
            <div 
              v-if="getPhotoList(row.photo).length > 0"
              class="image-preview-cell"
              @click="previewRescueImage(row)"
            >
              <el-image
                :src="getPhotoList(row.photo)[0]"
                fit="cover"
                style="width: 65px; height: 65px; border-radius: 8px; cursor: pointer; border: 2px solid #e4e7ed;"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <span v-if="getPhotoList(row.photo).length > 1" class="photo-count">
                {{ getPhotoList(row.photo).length }}
              </span>
            </div>
            <span v-else style="color: #909399;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="reporterId" label="上报人ID" width="100" align="center">
          <template #default="{ row }">
            <span>{{ row.reporterId || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="reportTime" label="上报时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatTime(row.reportTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              type="primary" 
              @click="openDialog(row)"
              :icon="Edit"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="del(row.id)"
              :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty 
        v-if="!loading && tableData.length === 0" 
        description="暂无救助记录"
        style="margin: 40px 0;"
      />

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑表单对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑救助记录' : '新增救助记录'" 
      width="700px"
      @close="handleDialogClose"
    >
      <el-form 
        ref="formRef"
        :model="form" 
        :rules="formRules" 
        label-width="100px"
      >
        <el-form-item label="动物类型" prop="animalType">
          <el-input 
            v-model="form.animalType" 
            placeholder="请输入动物类型，如：猫、狗、鸟等"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input 
            type="textarea" 
            v-model="form.description" 
            :rows="4"
            placeholder="请详细描述动物的状况、发现情况等信息"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="发现地点" prop="location">
          <el-input 
            v-model="form.location" 
            placeholder="请输入发现地点"
            clearable
          >
            <template #prefix>
              <el-icon><Location /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="现场照片" prop="photo">
          <el-upload
            class="upload-list"
            action="http://localhost:8080/api/rescue/uploadPhoto"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :file-list="photoList"
            list-type="picture-card"
            :limit="9"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="upload-tip">支持上传多张图片，最多9张（每张不超过5MB）</div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="选择状态" style="width: 100%;">
            <el-option label="待审核" :value="0" />
            <el-option label="进行中" :value="1" />
            <el-option label="已完成" :value="2" />
            <el-option label="驳回" :value="3" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="驳回原因" v-if="form.status === 3" prop="rejectReason">
          <el-input 
            type="textarea" 
            v-model="form.rejectReason" 
            :rows="3"
            placeholder="请输入驳回原因"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save" :loading="saving">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog 
      v-model="imagePreviewVisible" 
      title="图片预览" 
      width="90%"
      class="preview-dialog"
      @closed="handleImagePreviewClosed"
    >
      <div class="preview-container">
        <!-- 工具栏 -->
        <div class="preview-toolbar">
          <div class="toolbar-left">
            <el-button-group>
              <el-button @click="zoomOut" :icon="ZoomOut" :disabled="zoomScale <= 0.5" title="缩小">
                缩小
              </el-button>
              <el-button @click="resetZoom" title="重置">
                {{ Math.round(zoomScale * 100) }}%
              </el-button>
              <el-button @click="zoomIn" :icon="ZoomIn" :disabled="zoomScale >= 3" title="放大">
                放大
              </el-button>
            </el-button-group>
          </div>
          <div class="toolbar-right">
            <span class="preview-counter">
              共 {{ previewImageList.length }} 张图片，当前第 {{ previewImageIndex + 1 }} 张
            </span>
          </div>
        </div>
        
        <!-- 轮播容器 -->
        <div class="carousel-wrapper">
          <el-carousel 
            v-model="previewImageIndex"
            height="70vh"
            indicator-position="outside"
            @change="handleCarouselChange"
          >
            <el-carousel-item v-for="(url, index) in previewImageList" :key="index">
              <div class="carousel-image-wrapper" @wheel.prevent="handleWheel">
                <div 
                  class="image-zoom-container"
                  :style="{ transform: `scale(${zoomScale})` }"
                >
                  <img 
                    :src="url" 
                    class="preview-image"
                    alt="预览图片"
                    @load="handleImageLoad"
                    @error="handleImageError"
                  />
                </div>
              </div>
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Plus, Search, Refresh, Edit, Delete, Location, Picture, ZoomIn, ZoomOut } from '@element-plus/icons-vue'
import axios from 'axios'

const tableData = ref([])
const page = ref(1)
const size = ref(10)
const total = ref(0)
const loading = ref(false)
const saving = ref(false)
const searchKeyword = ref('')
const filterStatus = ref('')
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const photoList = ref([])

// 图片预览相关
const imagePreviewVisible = ref(false)
const previewImageList = ref([])
const previewImageIndex = ref(0)
const zoomScale = ref(1)

const form = ref({
  id: null,
  animalType: '',
  description: '',
  location: '',
  photo: '',
  status: 0,
  rejectReason: '',
  reporterId: null
})

const formRules = {
  animalType: [
    { required: true, message: '请输入动物类型', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入描述信息', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入发现地点', trigger: 'blur' }
  ]
}

const formatTime = (time) => {
  if (!time) return '-'
  if (typeof time === 'string' && time.includes('T')) {
    return time.replace('T', ' ').substring(0, 19)
  }
  return time
}

const getPhotoList = (photo) => {
  if (!photo) return []
  if (typeof photo === 'string') {
    return photo.split(',').filter(url => url.trim() !== '')
  }
  return Array.isArray(photo) ? photo : []
}

const getStatusText = (status) => {
  const statusMap = {
    0: '待审核',
    1: '进行中',
    2: '已完成',
    3: '驳回'
  }
  return statusMap[status] || '未知'
}

const getStatusType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'warning',
    2: 'success',
    3: 'danger'
  }
  return typeMap[status] || 'info'
}

async function loadData() {
  loading.value = true
  try {
    const params = {
      page: page.value,
      size: size.value
    }
    if (searchKeyword.value) {
      params.animalType = searchKeyword.value
    }
    if (filterStatus.value !== null && filterStatus.value !== '') {
      params.status = filterStatus.value
    }
    
    const res = await axios.get('http://localhost:8080/api/admin/rescue/list', { params })
    if (res.data.code === 200) {
      tableData.value = res.data.data || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.data.msg || '获取数据失败')
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取救助记录失败:', error)
    ElMessage.error('获取数据失败')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

function openDialog(row) {
  if (row) {
    isEdit.value = true
    form.value = { ...row }
    // 处理图片列表
    const photos = getPhotoList(row.photo)
    photoList.value = photos.map((url, index) => ({
      uid: index,
      name: `image-${index}.jpg`,
      url: url,
      status: 'success'
    }))
  } else {
    isEdit.value = false
    form.value = {
      id: null,
      animalType: '',
      description: '',
      location: '',
      photo: '',
      status: 0,
      rejectReason: '',
      reporterId: null
    }
    photoList.value = []
  }
  dialogVisible.value = true
}

function handleDialogClose() {
  formRef.value?.resetFields()
  form.value = {}
  photoList.value = []
}

function handleUploadSuccess(response, file) {
  let url = ''
  if (typeof response === 'string') {
    url = response
  } else if (response && response.url) {
    url = response.url
  } else if (response && response.code === 200 && response.data) {
    url = response.data.url || response.data
  } else if (response && response.data && response.data.url) {
    url = response.data.url
  }
  
  if (url) {
    const currentPhotos = form.value.photo ? form.value.photo.split(',').filter(u => u) : []
    currentPhotos.push(url)
    form.value.photo = currentPhotos.join(',')
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('上传失败：无法获取图片URL')
  }
}

function handleRemove(file) {
  const url = file.url || file.response?.url || file.response?.data?.url
  if (url && form.value.photo) {
    const photos = form.value.photo.split(',').filter(u => u && u !== url)
    form.value.photo = photos.join(',')
  }
}

async function save() {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请完善表单信息')
      return
    }
    
    saving.value = true
    try {
      const submitData = {
        ...form.value
      }
      
      // 如果没有驳回原因且状态是驳回，清空驳回原因
      if (submitData.status !== 3 && submitData.rejectReason) {
        submitData.rejectReason = ''
      }
      
      if (isEdit.value) {
        const res = await axios.put('http://localhost:8080/api/admin/rescue/update', submitData)
        if (res.data.code === 200) {
          ElMessage.success('更新成功')
          dialogVisible.value = false
          loadData()
        } else {
          ElMessage.error(res.data.msg || '更新失败')
        }
      } else {
        const res = await axios.post('http://localhost:8080/api/admin/rescue/add', submitData)
        if (res.data.code === 200) {
          ElMessage.success('添加成功')
          dialogVisible.value = false
          loadData()
        } else {
          ElMessage.error(res.data.msg || '添加失败')
        }
      }
    } catch (error) {
      console.error('保存失败:', error)
      ElMessage.error('保存失败：' + (error.response?.data?.msg || error.message || '未知错误'))
    } finally {
      saving.value = false
    }
  })
}

async function del(id) {
  try {
    await ElMessageBox.confirm('确定删除该记录吗？删除后无法恢复。', '提示', {
      type: 'warning',
      confirmButtonText: '确定删除',
      cancelButtonText: '取消'
    })
    
    const res = await axios.delete('http://localhost:8080/api/admin/rescue/delete', { 
      params: { ids: [id] },
      paramsSerializer: (params) => {
        const parts = []
        for (const key in params) {
          const value = params[key]
          if (Array.isArray(value)) {
            value.forEach(item => parts.push(`${key}=${encodeURIComponent(item)}`))
          } else {
            parts.push(`${key}=${encodeURIComponent(value)}`)
          }
        }
        return parts.join('&')
      }
    })
    if (res.data.code === 200) {
      ElMessage.success('删除成功')
      if (tableData.value.length === 1 && page.value > 1) {
        page.value--
      }
      loadData()
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleSearch = () => {
  page.value = 1
  loadData()
}

const handleReset = () => {
  searchKeyword.value = ''
  filterStatus.value = ''
  page.value = 1
  loadData()
}

const handleSizeChange = (newSize) => {
  size.value = newSize
  page.value = 1
  loadData()
}

const handleCurrentChange = (newPage) => {
  page.value = newPage
  loadData()
}

// 图片预览相关方法
const previewRescueImage = (row) => {
  const photoList = getPhotoList(row.photo)
  if (photoList.length > 0) {
    previewImageList.value = photoList.map(url => url.trim())
    previewImageIndex.value = 0
    zoomScale.value = 1
    imagePreviewVisible.value = true
  } else {
    ElMessage.warning('该记录没有图片')
  }
}

const zoomIn = () => {
  if (zoomScale.value < 3) {
    zoomScale.value = Math.min(zoomScale.value + 0.25, 3)
  }
}

const zoomOut = () => {
  if (zoomScale.value > 0.5) {
    zoomScale.value = Math.max(zoomScale.value - 0.25, 0.5)
  }
}

const resetZoom = () => {
  zoomScale.value = 1
}

const handleWheel = (event) => {
  event.preventDefault()
  if (event.deltaY < 0) {
    zoomIn()
  } else {
    zoomOut()
  }
}

const handleCarouselChange = () => {
  // 切换图片时保持当前缩放比例
}

const handleImagePreviewClosed = () => {
  previewImageList.value = []
  previewImageIndex.value = 0
  zoomScale.value = 1
}

const handleImageLoad = () => {
  // 图片加载完成处理
}

const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src)
  ElMessage.error('图片加载失败')
}

onMounted(loadData)
</script>

<style scoped>
.rescue-record-page {
  width: 100%;
}

.main-card {
  min-height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 22px;
  color: #409eff;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.code-text {
  font-family: 'Courier New', monospace;
  font-weight: 600;
  color: #409eff;
}

.location-cell {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
}

.location-cell .el-icon {
  color: #909399;
  font-size: 16px;
}

.image-preview-cell {
  display: inline-block;
  position: relative;
  cursor: pointer;
}

.image-preview-cell:hover {
  opacity: 0.8;
}

.photo-count {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #f56c6c;
  color: white;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 12px;
  font-weight: 600;
  line-height: 1.2;
  min-width: 20px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header) {
  background: #f5f7fa;
}

:deep(.el-table__header th) {
  background: #f5f7fa !important;
  border-bottom: 2px solid #e4e7ed;
  padding: 16px 0;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa !important;
}

:deep(.el-table__body td) {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table__row) {
  transition: all 0.3s;
}

:deep(.el-table__row:hover) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

/* 操作按钮组样式 */
:deep(.el-table__body .cell) {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: center;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.upload-tip {
  margin-top: 12px;
  color: #909399;
  font-size: 13px;
}
</style>

<!-- 预览对话框样式 -->
<style>
.preview-container {
  background: #1a1a1a;
  border-radius: 8px;
  overflow: hidden;
  padding: 20px;
}

.preview-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
}

.toolbar-left {
  display: flex;
  align-items: center;
}

.toolbar-right {
  display: flex;
  align-items: center;
}

.preview-counter {
  color: #fff;
  font-size: 14px;
  font-weight: 500;
}

.carousel-wrapper {
  position: relative;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

.carousel-image-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 70vh;
  overflow: auto;
  background: #000;
}

.image-zoom-container {
  display: inline-block;
  transition: transform 0.3s ease;
  transform-origin: center center;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
  display: block;
  user-select: none;
}

:deep(.preview-dialog .el-dialog) {
  margin: 5vh auto !important;
}

:deep(.preview-dialog .el-dialog__body) {
  padding: 20px !important;
  background: #1a1a1a;
}

:deep(.el-carousel__container) {
  height: 70vh !important;
}

:deep(.el-carousel__item) {
  height: 70vh !important;
}

:deep(.el-carousel__arrow) {
  background-color: rgba(255, 255, 255, 0.3);
  border: none;
}

:deep(.el-carousel__arrow:hover) {
  background-color: rgba(255, 255, 255, 0.5);
}

:deep(.el-carousel__indicators) {
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 20px;
  padding: 8px;
}
</style>
